from odbAccess import *
import csv
import os

def extract_elements_and_nodes(odb_path, output_folder):
    odb = openOdb(path=odb_path)
    last_step_name = odb.steps.keys()[-1]
    last_step = odb.steps[last_step_name]
    last_frame = last_step.frames[-1]

    output_file_name = odb_path + '.elements_nodes.csv'
    output_path = os.path.join(output_folder, output_file_name)
    csv_file = open(output_path, 'w')
    csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_NONE, escapechar=' ')
    csv_writer.writerow(['Element Label', 'Node Labels'])

    for instance in odb.rootAssembly.instances.values():
        for element in instance.elements:
            element_label = element.label
            #print(element.connectivity)
            node_labels = [node for node in element.connectivity]
            #print(node_labels )
            csv_writer.writerow([element_label, ', '.join(map(str, node_labels))])

    csv_file.close()
    odb.close()
    print("Data extracted and saved to "+ output_file_name)


if __name__ == "__main__":

    source_folder = '.' 
    target_folder = 'result'
    

    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    

    for filename in os.listdir(source_folder):
        if filename.endswith('.odb'):
            print("Processing "+filename+"...")
            odb_path = os.path.join(source_folder, filename)
            extract_elements_and_nodes(odb_path, target_folder)
            print("Done!")